package com.shujia.jinjie;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
import org.apache.hadoop.hbase.mapreduce.TableMapper;
import org.apache.hadoop.hbase.mapreduce.TableReducer;
import org.apache.hadoop.hbase.regionserver.BloomType;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;


/**
 * 编写hbase使用MR构建索引表的Map类
 * 由于原表是hbase中的数据文件，hfile文件，不是我们之前MR读写的普通数据文件
 * 使用原来的hadoop中的Mapper类读取数据，是行不通，读不懂的
 * 这里需要继承hbase专门提供读取hfile文件的Mapper类：TableMapper
 */
class MyIndexMapper extends TableMapper<Text,NullWritable>{
    @Override
    protected void map(ImmutableBytesWritable key, Result value, Mapper<ImmutableBytesWritable, Result, Text, NullWritable>.Context context) throws IOException, InterruptedException {
        //将姓名和学号作为映射关系建立索引表
        //获取原表的学号行键
        String id = Bytes.toString(value.getRow());
        //获取列值姓名
        String name = Bytes.toString(value.getValue(Bytes.toBytes("info"), Bytes.toBytes("name")));

        context.write(new Text(id+"-"+name),NullWritable.get());
    }
}


/**
 * 编写reduce类，将map任务的结果键，取出学号和姓名
 * 将姓名作为行键，学号作为列名，构建索引表
 */
class MyIndexReducer extends TableReducer<Text,NullWritable,NullWritable>{
    @Override
    protected void reduce(Text key, Iterable<NullWritable> values, Reducer<Text, NullWritable, NullWritable, Mutation>.Context context) throws IOException, InterruptedException {
        String s = key.toString();
        String id = s.split("-")[0];
        String name = s.split("-")[1];

        //创建Put对象
        Put put = new Put(Bytes.toBytes(name));
        put.addColumn(Bytes.toBytes("info"),Bytes.toBytes(id),Bytes.toBytes(""));

        context.write(NullWritable.get(),put);
    }
}


public class HbaseIndexDemo {
    public static void main(String[] args) throws Exception{
        //创建配置文件对象
        Configuration conf = HBaseConfiguration.create();
        //指定zookeeper的配置信息
        conf.set("hbase.zookeeper.quorum", "master:2181,node1:2181,node2:2181");
        //创建Job作业对象
        Job job = Job.getInstance(conf);
        job.setJobName("给学生表创建二级索引表");

        job.setJarByClass(HbaseIndexDemo.class);
        //因为索引表的构建是建立列值与行键的映射关系，要获取所有的数据
        //scan扫描全表数据
        Scan scan = new Scan();
        //告诉输入的列值来自于哪一个列簇
        scan.addFamily(Bytes.toBytes("info"));

        //先将表名封装成一个TableName的对象
        Connection conn = ConnectionFactory.createConnection(conf);
        Admin admin = conn.getAdmin();

        //先将表名封装成一个TableName的对象
        TableName tn = TableName.valueOf("students_index");
        if (!admin.tableExists(tn)) {
            TableDescriptorBuilder studentsIndex = TableDescriptorBuilder.newBuilder(tn);

            //使用另外一种方式创建列簇并设置布隆过滤器
            ColumnFamilyDescriptor columnFamilyDescriptor = ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes("info"))
                    .setBloomFilterType(BloomType.ROW).build();
            studentsIndex.setColumnFamily(columnFamilyDescriptor);
            admin.createTable(studentsIndex.build());
            System.out.println(tn + "表创建成功！！！");
        } else {
            System.out.println(tn + "表已经存在！");
        }


        //索引表是执行完MR作业后产生的
        /**
         /**
         * Use this before submitting a TableMap job. It will appropriately set up
         * the job.
         *
         * @param table  The table name to read from.
         * @param scan  The scan instance with the columns, time range etc.
         * @param mapper  The mapper class to use.
         * @param outputKeyClass  The class of the output key.
         * @param outputValueClass  The class of the output value.
         * @param job  The current job to adjust.  Make sure the passed job is
         * carrying all necessary HBase configuration.
         * @throws IOException When setting up the details fails.
         *public static void initTableMapperJob
         * (String table,Scan scan,Class<? extends TableMapper> mapper,Class<?> outputKeyClass,Class<?> outputValueClass,Job job)
         */
        TableMapReduceUtil.initTableMapperJob("students", scan, MyIndexMapper.class, Text.class, NullWritable.class, job);

        TableMapReduceUtil.initTableReducerJob("students_index", MyIndexReducer.class, job);

        //提交作业到集群中允许
        boolean b = job.waitForCompletion(true);
        if (b) {
            System.out.println("================== students索引表构建成功！！！============================");
        } else {
            System.out.println("================== students索引表构建失败！！！============================");
        }
    }
}
